"""
增强版Kubernetes资源合并器
"""
from typing import Dict, List, Any, Optional
import copy
import logging

class EnhancedResourceMerger:
    """增强版资源合并器"""
    
    def __init__(self):
        """初始化合并器"""
        self.logger = logging.getLogger(__name__)
        self.strategy = "deep"  # deep, shallow, custom
    
    def merge(
        self,
        resources: List[Dict[str, Any]],
        strategy: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        合并多个资源
        
        Args:
            resources: 资源列表
            strategy: 合并策略
            
        Returns:
            合并后的资源
        """
        if not resources:
            return {}
        
        # 使用指定的策略
        strategy = strategy or self.strategy
        
        if strategy == "deep":
            return self._deep_merge(resources)
        elif strategy == "shallow":
            return self._shallow_merge(resources)
        elif strategy == "custom":
            return self._custom_merge(resources)
        else:
            raise ValueError(f"不支持的合并策略: {strategy}")
    
    def _deep_merge(self, resources: List[Dict[str, Any]]) -> Dict[str, Any]:
        """深度合并"""
        result = copy.deepcopy(resources[0])
        
        for resource in resources[1:]:
            self._merge_dict(result, resource)
        
        return result
    
    def _shallow_merge(self, resources: List[Dict[str, Any]]) -> Dict[str, Any]:
        """浅层合并"""
        result = {}
        
        for resource in resources:
            result.update(resource)
        
        return result
    
    def _custom_merge(self, resources: List[Dict[str, Any]]) -> Dict[str, Any]:
        """自定义合并策略"""
        # 默认实现与深度合并相同
        return self._deep_merge(resources)
    
    def _merge_dict(self, target: Dict[str, Any], source: Dict[str, Any]) -> None:
        """
        合并字典
        
        Args:
            target: 目标字典
            source: 源字典
        """
        for key, value in source.items():
            if key in target:
                if isinstance(target[key], dict) and isinstance(value, dict):
                    self._merge_dict(target[key], value)
                elif isinstance(target[key], list) and isinstance(value, list):
                    target[key].extend(value)
                else:
                    target[key] = value
            else:
                target[key] = copy.deepcopy(value)
    
    def merge_with_strategy(
        self,
        resources: List[Dict[str, Any]],
        strategy_config: Dict[str, str]
    ) -> Dict[str, Any]:
        """
        使用自定义策略合并资源
        
        Args:
            resources: 资源列表
            strategy_config: 策略配置
            
        Returns:
            合并后的资源
        """
        result = copy.deepcopy(resources[0])
        
        for resource in resources[1:]:
            for path, strategy in strategy_config.items():
                self._apply_strategy(result, resource, path, strategy)
        
        return result
    
    def _apply_strategy(
        self,
        target: Dict[str, Any],
        source: Dict[str, Any],
        path: str,
        strategy: str
    ) -> None:
        """
        应用合并策略
        
        Args:
            target: 目标资源
            source: 源资源
            path: 路径
            strategy: 策略
        """
        # 解析路径
        parts = path.split(".")
        current_target = target
        current_source = source
        
        # 导航到目标位置
        for part in parts[:-1]:
            if part not in current_target:
                current_target[part] = {}
            if part not in current_source:
                return
            current_target = current_target[part]
            current_source = current_source[part]
        
        # 获取最后一个部分
        last_part = parts[-1]
        
        # 应用策略
        if strategy == "replace":
            if last_part in current_source:
                current_target[last_part] = copy.deepcopy(current_source[last_part])
        elif strategy == "merge":
            if last_part in current_source:
                if isinstance(current_target.get(last_part), dict) and isinstance(current_source[last_part], dict):
                    if last_part not in current_target:
                        current_target[last_part] = {}
                    self._merge_dict(current_target[last_part], current_source[last_part])
                elif isinstance(current_target.get(last_part), list) and isinstance(current_source[last_part], list):
                    if last_part not in current_target:
                        current_target[last_part] = []
                    current_target[last_part].extend(current_source[last_part])
        elif strategy == "append":
            if last_part in current_source:
                if isinstance(current_target.get(last_part), list) and isinstance(current_source[last_part], list):
                    if last_part not in current_target:
                        current_target[last_part] = []
                    current_target[last_part].extend(current_source[last_part])
        elif strategy == "prepend":
            if last_part in current_source:
                if isinstance(current_target.get(last_part), list) and isinstance(current_source[last_part], list):
                    if last_part not in current_target:
                        current_target[last_part] = []
                    current_target[last_part] = current_source[last_part] + current_target[last_part]
        else:
            raise ValueError(f"不支持的策略: {strategy}") 